package com.slkj.shilixiaoyuanapp.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.Image;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.slkj.shilixiaoyuanapp.R;
import com.slkj.shilixiaoyuanapp.util.AutoDensityUtils;
import com.slkj.shilixiaoyuanapp.view.dialog.LoadSuccessAndFailDialog;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;

/**
 * Created  on 2018/6/25 0025
 *
 * @author 唐开阔
 * @describe
 */
public abstract class BaseActivity extends RxAppCompatActivity {
    protected final  String TAG = this.getClass().getSimpleName();
    private TextView tvTitle, tvRight;
    private ImageView imageBack,imgMore;
    public Unbinder unbinder;
    String FRAGMENTS_TAG = "android:support:fragments";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /**
         * 不保存fragment实例，每次都新建
         */
        if (savedInstanceState != null) {
            savedInstanceState.putParcelable(FRAGMENTS_TAG, null);
        }
        AutoDensityUtils.setCustomDensity(this);
        ActivityInfo activityInfo = getClass().getAnnotation(ActivityInfo.class);
        if (activityInfo.isFullscreen()) {
            this.requestWindowFeature(Window.FEATURE_NO_TITLE);
            this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getSupportActionBar().hide();
        }
        setRequestedOrientation(SCREEN_ORIENTATION_PORTRAIT);

        setContentView(activityInfo.layout());
        if (!activityInfo.isShowActionBar()) {
            getSupportActionBar().hide();
        } else {
            ActionBar actionBar = getSupportActionBar();
            ActionBar.LayoutParams lp =new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT, Gravity.CENTER);
            View mActionBarView = LayoutInflater.from(this).inflate(R.layout.layout_actionbar, null);
            actionBar.setCustomView(mActionBarView,lp);
            actionBar.setElevation(0);
            actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
            actionBar.setDisplayShowCustomEnabled(true);
            actionBar.setDisplayShowHomeEnabled(false);
            actionBar.setDisplayShowTitleEnabled(false);

            imgMore = mActionBarView.findViewById(R.id.img_more);

            tvTitle = mActionBarView.findViewById(R.id.tv_title);
            tvRight = mActionBarView.findViewById(R.id.tv_right_hint);
            mActionBarView.findViewById(R.id.layout_back).setOnClickListener(v -> onBackPressed());
            tvTitle.setText(activityInfo.title());
            tvRight.setText(activityInfo.rightHint());
            tvRight.setOnClickListener(v -> onRightTitleClick());
            imgMore.setOnClickListener(v -> onRightTitleClick());

            if (activityInfo.isShowMore()){
                tvRight.setVisibility(View.GONE);
                imgMore.setVisibility(View.VISIBLE);
            }else {
                imgMore .setVisibility(View.GONE);
                tvRight.setVisibility(View.VISIBLE);
            }


        }
        unbinder = ButterKnife.bind(this);
        init(savedInstanceState);
        init();
    }

    public TextView getTvRight() {
        return tvRight;
    }
    public ImageView getImgRight() {
        return imgMore;
    }
    protected void onRightTitleClick() {

    }
    public void setRightTitleColor(int color) {
        tvRight.setTextColor(color);
    }

    ;

    /**
     * 初始化
     */
    protected abstract void init();

    protected void init(Bundle savedInstanceState) {

    }

    ;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }
    public void setTitle(String title) {
        tvTitle.setText(title);
    }
    protected void showToast(String mes) {
        LoadSuccessAndFailDialog.showFail(this,mes);


    }

    /**
     * 便捷指定线程
     *
     * @param <T>
     * @return
     */
    public <T> ObservableTransformer<T, T> getThread() {
        return upstream -> upstream.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
    }

    /**
     * 跳转
     *
     * @param cla
     */
    public void startActivity(Class cla) {
        Intent intent = new Intent(this, cla);
        super.startActivity(intent);
    }

    /**
     * 点击键盘以外区域，收起键盘
     * @param ev
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        try {
            if (ev.getAction() == MotionEvent.ACTION_DOWN) {
                View v = getCurrentFocus();
                if (isShouldHideInput(v, ev)) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm != null) {
                        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    }
                }
                return super.dispatchTouchEvent(ev);
            }
            // 必不可少，否则所有的组件都不会有TouchEvent了
            if (getWindow().superDispatchTouchEvent(ev)) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return onTouchEvent(ev);
        }
    }

    protected boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                //使EditText触发一次失去焦点事件
                v.setFocusable(false);
                v.setFocusableInTouchMode(true);
                return true;
            }
        }
        return false;
    }

    public void clearContent(){
        finish();
        Intent intent = new Intent(this, getClass());
       startActivity(intent);
       overridePendingTransition(0, 0);


    }

    @Override
    protected void onPause() {
        super.onPause();

    }
}
